package com.tgy.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 */
public class _3_无重复字符的最长子串 {

    public static int lengthOfLongestSubstring(String s) {

        if (s == null || s.length() == 0) {

            return 0;
        }

        if (s.length() == 1) {

            return 1;
        }

        char[] chars = s.toCharArray();
        int len = chars.length;
        int left = 0,right = 0;
        Map<Character,Integer> map = new HashMap<>();
        int res = 0;

        while (right < len) {

            char key = chars[right];
            Integer count = map.get(key);

            if (count != null && count > 0) {

                char leftKey = chars[left];
                while (left < right && leftKey != key) {

                    map.put(chars[left],map.get(leftKey) - 1);
                    left++;
                    leftKey = chars[left];
                }

                if (left < right) {
                    left++;
                }

            }else {

                map.put(key,1);
            }

            res = Math.max(res,right - left + 1);
            right++;
        }

        return res;
    }

    public static void main(String[] args) {

//        String s = "pwwkew";
//        String s = "ppppppp";
        String s = "  ";
        System.out.println(lengthOfLongestSubstring(s));
    }

}
